package com.justgame.project.service.system.service;

import com.justgame.project.base.auth.Auth2Realm;
import com.justgame.project.base.utils.CheckAccount;
import com.justgame.project.base.utils.EmailUtil;
import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.constant.Regex;
import com.justgame.project.cloud.common.enums.TimeEnum;
import com.justgame.project.cloud.common.exception.Exc;
import com.justgame.project.cloud.common.util.*;
import com.justgame.project.cloud.common.entity.PageRequest;
import com.justgame.project.service.api.dto.LoginedInfoModel;
import com.justgame.project.service.api.dto.OnlineUserInfoDTO;
import com.justgame.project.service.api.dto.SysUserInfoDTO;
import com.justgame.project.service.api.entity.SysUserInfo;
import com.justgame.project.service.api.feign.IOnlineUserClient;
import com.justgame.project.service.api.vo.OnlineUserInfoVO;
import com.justgame.project.service.system.mapper.SysUserInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SysUserInfoService {

    @Resource
    private IOnlineUserClient onlineClient;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SysUserInfoMapper sysUserInfoMapper;

    /**
     * 刷新Token中存储关于用户相关信息
     *
     * @param userId
     */
    public static void doRedisUserInfo(String userId) {
        /* 获取在Spring下维护的Bean实例 */
        SysUserInfoMapper sysUserInfoMapper = AppContextUtils.getBean(SysUserInfoMapper.class);
        RedisUtil redisUtil = AppContextUtils.getBean(RedisUtil.class);
        /* 获取用户信息 */
        SysUserInfo user = sysUserInfoMapper.selectUserInfoById(userId);
        if (user != null) {
            redisUtil.delete(Const.KEY_REDIS_TOTAL_USER + userId);
            redisUtil.set(Const.KEY_REDIS_TOTAL_USER + userId, user, TimeEnum.HOUR.getTime(1) / 1000);
        }
    }

    public PageRequest<OnlineUserInfoVO> queryByPage(PageRequest<OnlineUserInfoVO> pageRequest) {
        if (pageRequest.getPage() != 0 && pageRequest.getSize() != 0) {
            pageRequest.startPage();
            List<OnlineUserInfoVO> list = sysUserInfoMapper.queryAll();
            return pageRequest.BuildPageInfo(list);
        } else {
            throw new Exc("参数不合规");
        }
    }

    /**
     * 用户注册服务
     *
     * @param dto
     * @return
     */
    public Boolean createAccount(SysUserInfoDTO dto) {
        if (Regex.hasChinese(dto.getAccount()) || Regex.hasChinese(dto.getPassword())) {
            throw new Exc("账号或密码不能含有中文，请重新输入。");
        }
        if (Regex.isSymbol(dto.getAccount())) {
            throw new Exc("账号中不能含有特殊符号。");
        }
        if (sysUserInfoMapper.hasSameKv("uname", dto.getAccount()) > 0) {
            throw new Exc("该账户名已存在，请重新输入！");
        } else if (sysUserInfoMapper.hasSameKv("email", dto.getEmail()) > 0) {
            throw new Exc("该邮箱已被使用，请重新输入！");
        } else if (sysUserInfoMapper.hasSameKv("phone", dto.getEmail()) > 0) {
            throw new Exc("该手机号已被使用，请重新输入！");
        }
        /* 检查邮箱验证码 */
        EmailUtil.checkMailCode(dto.getEmail(), dto.getMailCode());
        /* 构建注册用户信息 */
        SysUserInfoDTO newUser = new SysUserInfoDTO();
        newUser.setId(IdUtils.create());
        newUser.setUname(dto.getAccount());
        newUser.setUpwd(String.valueOf(Encryption.PasswordMD5(dto.getPassword())));
        newUser.setSex(0);
        newUser.setStatusId(200);
        newUser.setOnlineId(IdUtils.uniqueId());
        newUser.setPhone(dto.getPhone());
        newUser.setEmail(dto.getEmail());
        newUser.setCreateUser(newUser.getId());
        newUser.setCreateDate(new Date());
        /* 保存至数据库 */
        if (sysUserInfoMapper.createAccount(newUser) == 0) {
            return false;
        } else {
            /* 刷新缓存中的用户信息 */
            doRedisUserInfo(newUser.getId());
            /* 生成online_user_info表信息 */
            boolean temp = onlineClient.saveOnlineUser(newUser.buildNewOnlineUser());
            if (temp) {
                /* 向注册邮箱发送注册成功通知 */
                EmailUtil.success2Sign(dto.getEmail(), dto.getAccount());
            }
            return temp;
        }
    }

    /**
     * 获取所有的账户id+账户名uname
     *
     * @return
     */
    public List<SysUserInfo> getAllAccountId() {
        List<SysUserInfo> list = sysUserInfoMapper.selectAllAccountsId();
        return list;
    }

    /**
     * 通过账号ID获取账户信息
     *
     * @param uid
     * @return
     */
    public SysUserInfo getUseInfoById(String uid) {
        if (!StringUtils.isEmpty(uid)) {
            return sysUserInfoMapper.selectUserInfoById(uid);
        } else {
            return new SysUserInfo();
        }
    }

    /**
     * 退出登录
     **/
    public boolean logout() {
        try {
            String userId = ShiroUtils.getUserId();
            ShiroUtils.delToken(TokenUtil.getToken(),userId);
            ShiroUtils.getSubject().logout();
            HttpSession session = HttpContextUtil.getSession();
            /* 此处Session属性会在ResponseListener移除 */
            session.setAttribute("temp_userId", userId);
            redisUtil.delete(Const.KEY_REDIS_TOTAL_USER + userId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 邮箱变更
     *
     * @param dto
     * @return
     */
    public boolean changeEmail(SysUserInfoDTO dto) {
        /* 获取用户id */
        String userId = ShiroUtils.getUserId();

        /* 验证字段 */
        if (StringUtils.isBlank(userId)) {
            throw new Exc("请先登录后再试！");
        }
        EmailUtil.checkMailCode(dto.getEmail(), dto.getMailCode());
        boolean emailHasUsed = sysUserInfoMapper.countsOfEmail(dto.getEmail()) > 0;
        if (emailHasUsed) {
            throw new Exc("该邮箱已被使用，无法绑定！");
        }
        /* 准备工作完毕，创建一个用于更新的对象 */
        SysUserInfoDTO updateObj = new SysUserInfoDTO();
        updateObj.setId(userId);
        updateObj.setEmail(dto.getEmail());
        /* 先查询旧邮箱，通知该邮箱已换绑 */
        SysUserInfo userInfo = sysUserInfoMapper.selectUserInfoById(userId);
        if (userInfo == null) {
            throw new Exc("账户信息不存在，请重新登录。若依旧存在此问题请联系管理者！");
        }
        /* 更新 */
        boolean temp = sysUserInfoMapper.updateById(updateObj) > 0;
        /* 通知双方 */
        if (StringUtils.isNotBlank(userInfo.getEmail()) && temp) {
            EmailUtil.emailHasChanged(dto.getEmail(), TimeUtil.simpleDateNow());
        }
        if (temp) {
            EmailUtil.success2ChangeEmail(dto.getEmail(), userInfo.getUname());
        }
        return temp;
    }

    public LoginedInfoModel regainUserInfo() {
        String userId = ShiroUtils.getUserId();
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        LoginedInfoModel user = sysUserInfoMapper.regainUserInfo(userId);
        if (user == null || user.getUserid() == null) {
            return null;
        }

        /* 查看有没有被封号 */
        if (Auth2Realm.BAN.contains(Integer.valueOf(user.getStatusId()))) {
            throw new Exc("您的账号已被封禁！", Const.CODE_TOKEN_OUTDATED);
        }

        String oldToken = ShiroUtils.getToken();
        if (StringUtils.isBlank(oldToken) || TokenUtil.hasExpired(oldToken, Const.DEFAULT_SALT_TOKEN)) {
            oldToken = redisUtil.get(Const.KEY_REDIS_TOKEN_CURRENT + userId);
            if (StringUtils.isBlank(oldToken) || TokenUtil.hasExpired(oldToken, Const.DEFAULT_SALT_TOKEN)) {
                /* 颁发Token */
                String token = new TokenUtil().generate(user.getUserid(), Const.DEFAULT_SALT_TOKEN, Const.TIME_TIMEOUT_TOKEN);
                ShiroUtils.addToken(token, user.getUserid());
                ShiroUtils.login(token);
                return new LoginedInfoModel(user, token);
            }
        }
        return new LoginedInfoModel(user, oldToken);
    }

    /**
     * 登陆Service
     *
     * @param loginUserModel
     * @return
     */
    public LoginedInfoModel login(SysUserInfoDTO loginUserModel) {
        String account = loginUserModel.getAccount();
        String password = Encryption.Base64Decode(loginUserModel.getPassword());
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            throw new Exc("账号或密码不能为空");
        }
        loginUserModel.setPassword(String.valueOf(Encryption.PasswordMD5(password)));
        LoginedInfoModel user;
        switch (CheckAccount.LogingWay(account)) {
            //     邮箱
            case 1:
                user = sysUserInfoMapper.loginByEmail(loginUserModel);
                break;
            //     手机
            case 2:
                user = sysUserInfoMapper.loginByPhone(loginUserModel);
                break;
            //     账号
            case 3:
                user = sysUserInfoMapper.loginByAccount(loginUserModel);
                break;
            case -1:
            default:
                throw new Exc("账号格式不正确");
        }

        if (user == null || user.getUserid() == null) {
            throw new Exc("账号密码不正确或者账号不存在");
        }

        /* 查看有没有被封号 */
        if (Auth2Realm.BAN.contains(Integer.valueOf(user.getStatusId()))) {
            throw new Exc("您的账号已被封禁，因此您暂时无法登录。");
        }
        /* 更新最后登录日期为此时 */
        OnlineUserInfoDTO dto = new OnlineUserInfoDTO();
        dto.setOnlineId(Long.valueOf(user.getOnlineId()));
        dto.setFinalDate(LocalDateTime.now());
        onlineClient.updateById(dto);
        /* 刷新缓存中的用户信息 */
        doRedisUserInfo(user.getUserid());
        /* 颁发Token */
        String token = new TokenUtil().generate(user.getUserid(), Const.DEFAULT_SALT_TOKEN, Const.TIME_TIMEOUT_TOKEN);
        ShiroUtils.addToken(token, user.getUserid());
        ShiroUtils.login(token);
        return new LoginedInfoModel(user, token);
    }

}
